<?php
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */

namespace App\Controller\Api;

use App\Service\WechatService;
use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 *
 * @Controller(prefix="api/wx")
 * 公众号相关操作
 * Class WechatController
 */
class WxController
{
    /**
     * @Inject()
     * @var WechatService
     */
    protected $wechatService;

    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;


    /**
     * 获取预支付返回信息
     * @PostMapping(path="pay")
     * @param string $client
     * @param $openId
     * @param $data
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay()
    {
        $header = $this->request->getHeaders();

        //下单逻辑
        //TODO
        $orderId = 0;

        //这里写商品和订单信息，我们模拟用前端传参给测试一下
        $data=$this->request->all();

        $client=$header['client-type'][0];
        $openId = $header['openid'][0];
        $payType = ($client =='lite'|| $client=='h5')? 'JSAPI' : $client;//lite小程序支付
        $predata=[];
        $serverParams = $this->request->getServerParams();
        $ip = $serverParams['remote_addr']??'';
        $outTradeNo = for_out_trade_no();
        $data['order_sn'] = $outTradeNo;
        switch ($client){
            case 'app':
                $predata =[
                    'trade_type' => $payType,
                    'out_trade_no' => $outTradeNo,
                    'body'=>$data['body'],
                    'total_fee'=> $data['price'],
                    'spbill_create_ip' => $ip,
                    'attach' =>json_encode(['module'=>$data['module'],'pay_queue'=>$orderId])//"{\"module\":\"goods_order\",\"pay_queue\":$data['order_id}" ,
                ];
                break;
            case 'mp' :
                $predata =[
                    'trade_type' => $payType,
                    'out_trade_no' => $outTradeNo,
                    'body'=>$data['body'],
                    'total_fee'=> $data['price'],
                    'openid' => $openId,
                    'spbill_create_ip' => $ip,
                    'attach' =>json_encode(['module'=>$data['module'],'pay_queue'=>$orderId])//"{\"module\":\"goods_order\",\"pay_queue\":$data['order_id}" ,
                ];
                break;
            case 'h5':
                $predata =[
                    'trade_type' => $payType,
                    'out_trade_no' => $outTradeNo,
                    'body'=>$data['body'],
                    'total_fee'=> $data['price'],
                    'openid' => $openId,
                    'spbill_create_ip' => $ip,
                    'attach' =>json_encode(['module'=>$data['module'],'pay_queue'=>$orderId])//"{\"module\":\"goods_order\",\"pay_queue\":$data['order_id}" ,
                ];
                break;

            case 'pc':
                $predata =[
                    'trade_type' => 'NATIVE',
                    'out_trade_no' => $outTradeNo,
                    'body'=>$data['body'],
                    'total_fee'=> $data['price'],
                    'spbill_create_ip' => $ip,
                    'attach' =>json_encode(['module'=>$data['module'],'pay_queue'=>$orderId])//"{\"module\":\"goods_order\",\"pay_queue\":$data['order_id}" ,
                ];
                break;
        }

        if(!empty($predata)){
            $prepay = $this->wechatService->unifyPay($predata);
            if($prepay['return_code'] =='SUCCESS' && $prepay['result_code'] =='SUCCESS'){

                if($client=='APP'){
                    //app支付直接返回

                    $payData['appid']=$prepay['appid'];
                    $payData['partnerid']=$prepay['mch_id'];
                    $payData['timestamp'] = $prepay['timeStamp'] =time().'';
                    $payData['noncestr'] = $prepay['nonceStr'] = for_random_string(32);
                    $payData['prepayid'] = $prepay['prepay_id'];
                    $payData['package'] = 'Sign=WXPay';
                    $paySign = $this->wechatService->makeSign($payData,'MD5');//支付加密用MD5，分账的是sha256
                    $prepay['sign'] = $paySign;
                    $prepay['order_sn'] = $data['order_sn'];
                    return Result::success($prepay);

                }else if($client == 'lite'){
                    //第二次加密，注意参数驼峰法
                    //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_10&index=1

                    $payData['appId']=$prepay['appid'];
                    $payData['timeStamp']=time().'';
                    $payData['nonceStr'] = for_random_string(32);
                    $payData['package'] = 'prepay_id='.$prepay['prepay_id'];
                    $payData['signType'] = 'MD5';
                    $paySign = $this->wechatService->makeSign($payData,'MD5');//支付加密用MD5，分账的是sha256
                    $payData['order_sn'] = $data['order_sn'];
                    $payData['sign'] = $paySign;
                    return Result::success($payData);

                }else if($client == 'h5'){
                    if(strpos(strtolower($header['user-agent'][0]),'micromessenger')!=false){
                        //微信浏览器
                        $payData['appId']=$prepay['appid'];
                        $payData['timeStamp']=time().'';
                        $payData['nonceStr'] = for_random_string(32);
                        $payData['package'] = 'prepay_id='.$prepay['prepay_id'];
                        $payData['signType'] = 'MD5';
                        $paySign = $this->wechatService->makeSign($payData,'MD5');//支付加密用MD5，分账的是sha256
                        $payData['order_sn'] = $data['order_sn'];
                        $payData['sign'] = $paySign;
                    }else{
                        $payData['appId']=$prepay['appid'];
                        $payData['timeStamp']=time().'';
                        $payData['nonceStr'] = $prepay['nonce_str'];
                        $payData['package'] = $prepay['prepay_id'];
                        $payData['trade_type'] = $prepay['trade_type'];
                        $payData['mweb_url'] = $prepay['mweb_url'];
                        $payData['order_sn'] = $data['order_sn'];
                    }

                    return Result::success($payData);
                }else if($client == 'pc'){
                    return Result::success($prepay);
                }
            }else{
                return Result::error('提交订单失败');
            }
        }else{
            return Result::error('参数异常');
        }
    }
    /**
     * @RequestMapping(path="create/menu",methods={"post","get"})
     */
    public function createMenu(RequestInterface $request)
    {
        $params = $request->all();
        $res = $this->wechatService->createMenu($params['button']);
        //var_dump($params,$res);
        if(isset($res['errcode']) && $res['errcode']!=0){
            return Result::error($res['errmsg']);
        }else{
            return Result::success();
        }
    }

    /**
     * @GetMapping(path="share/config")
     */
    public function getShareConfig()
    {
        $url = $this->request->query('url');
        $wechat = new WechatService('h5',[]);
        $res = $wechat->officialConfig($url,false,for_get_host($this->request->getHeaders()));
        return Result::success(json_decode($res));
    }

    /**
     * 获取支持的行业列表
     * @GetMapping(path="get/industry")
     */
    public function getIndustry()
    {
        $res = $this->wechatService->getIndustry();
    }
    /**
     * 添加模板 在公众号后台获取 $shortId 并添加到账户。
     * @GetMapping(path="add/template")
     */
    public function addTemplate()
    {
        $res = $this->wechatService->addTemplate($this->request->query('short_id'));
    }
    /**
     * 获取所有模板列表
     * @GetMapping(path="get/template")
     */
    public function getPrivateTemplates()
    {
        $res =  $this->wechatService->getPrivateTemplates();
    }

    /**
     * 推送模板消息
     * @GetMapping(path="send/templatemsg")
     */
    public function send()
    {
        $params = $this->request->all();
        $templateId = 'LxItHDqUS_lgCwxYDjIXGDhNeF2tXePGsMA1630KfEA';
        $openId = 'oYUCe6kTxt9j45Br_1wh2R8nPwT0';
        $msg = [
            'touser' => $openId,
            'template_id' => $templateId,
            'data' => [
                'keyword1' => 'VALUE',
                'keyword2' => '你好',  // 不需要指定颜色
                'keyword3' => ['你好', '#F00'], // 指定为红色
                'keyword4' => ['value' => '你好', 'color' => '#550038'], // 与第二种一样
                'keyword5' => ['value' => '你好'], // 与第一种一样,
                'remark' => '备注'
            ]
        ];
        return $this->wechatService->sendTemplate($msg);
    }
    /**
     * @GetMapping(path="send/subscriptionmsg")
     * 发送模板消息
     * [
    'touser' => 'user-openid',
    'template_id' => 'template-id',
    'url' => 'https://easywechat.org',
    'scene' => 1000,
    'data' => [
    'key1' => 'VALUE',
    'foo' => '你好',  // 不需要指定颜色
    'bar' => ['你好', '#F00'], // 指定为红色
    'baz' => ['value' => '你好', 'color' => '#550038'], // 与第二种一样
    'zoo' => ['value' => '你好'], // 与第一种一样,
    ...
    ]],
     */
    public function sendSubscription()
    {
        $params = $this->request->all();
        $msg = [

        ];
        return $this->wechatService->sendSubscription($msg);
    }

    /**
     * @GetMapping(path="customer/service")
     */
    public function customerService(RequestInterface $request)
    {
        $params = $request->all();
        $res = $this->wechatService->transfer($params['msg'],$params['account']);
        if($res->getStatusCode()==200){
            return "SUCCESS";
        }else{
            return "异常";
        }
    }
}